package com.cxm.report.model.event;

import com.cxm.report.model.IReport;
import com.cxm.report.model.data.Report;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;

/**
 * 数据表准备监听器
 * @author scl
 *
 */
@Component
@Slf4j
public class MailListener implements ApplicationListener<MailEvent>{
    @Value("${spring.mail.to}")
    private String mailTo;
    @Value("${spring.mail.cc}")
    private String mailCc;
    private  String[] ccs;
	@Autowired
	private JavaMailSenderImpl sender;
	@Autowired
	private TemplateEngine templateEngine;
	@PostConstruct
    private void init(){
        try {
            if (StringUtils.hasText(mailCc)){
                ccs = mailCc.split(",");
            }
        } catch (Exception e) { }
    }
    @Async
	@Override
	public void onApplicationEvent(MailEvent event) {

        Report report = (Report) event.getSource();
        try {
            MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
                helper.setFrom(sender.getUsername());
                helper.setTo(mailTo);
                //添加抄送人
                addCs(helper);

                IReport.Type reportType = report.getType();
                helper.setSubject(report.getDate()+reportType.getTitle());

                Context context = new Context();
                context.setVariable("report",report);

                String mailTemplate = templateEngine.process(reportType.getTemplate(), context);

                helper.setText(mailTemplate,true);
            };
            sender.send(mimeMessagePreparator);
            log.info("邮件发送完成");

        } catch (Exception e) {
            log.error("邮件发送失败",e);
        }
	}

    private void addCs(MimeMessageHelper helper) throws MessagingException {
        if (ccs != null && ccs.length > 0){
            for (String cc : ccs) {
                helper.addCc(cc);
            }
        }
    }
}
